// ignore_for_file: use_build_context_synchronously

import 'dart:async';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:video_ducafecat_flutter_v3/common/index.dart';

/// 录音组件
/// 实现了一个完整的录音功能，用户长按按钮即可进行录音，支持录音过程中的状态提示和手势操作，
/// 并在录音结束后提供发送音频或取消发送的选项。
class ChatBarSendSoundWidget extends StatefulWidget {
  const ChatBarSendSoundWidget({
    super.key,
    this.onSoundSend,
    required this.onDownBottom,
  });

  /// 发送音频
  final Function(String path, int seconds)? onSoundSend;

  /// 关闭语音输入
  final Function() onDownBottom;

  @override
  State<ChatBarSendSoundWidget> createState() => _ChatBarSendSoundWidgetState();
}

class _ChatBarSendSoundWidgetState extends State<ChatBarSendSoundWidget> {
  /// 浮动提示文字
  String soundTipsText = "";

  /// 是否正在录音
  bool isRecording = false;

  /// 是否初始化
  bool isInit = false;

  /// 是否取消发送
  bool isCancelSend = false;

  /// 开始时间
  DateTime startTime = DateTime.now();

  /// 订阅消息
  List<StreamSubscription<Object>> subscriptions = [];

  /// 录音提示层
  OverlayEntry? overlayEntry;

  /// 音量
  double volume = 0.1;

  /// 录音工具类
  SoundRecorder recorder = SoundRecorder();

  //////////////////////////////////////////////////////////////
  /// 内部业务函数

  /// 初始化
  Future<void> _initRecordSound() async {
    // 监听录音状态
    final responseSubscription = recorder.responseListener((recordResponse) {
      final status = recordResponse.msg;
      if (status == "onStop") {
        if (!isCancelSend) {
          final soundPath = recordResponse.path;
          final recordDuration = recordResponse.audioTimeLength;
          // 发送
          _sendSound(
            path: soundPath!,
            duration: recordDuration!.ceil(),
          );
        }
      } else if (status == "onStart") {
        log("start record");
        setState(() {
          isRecording = true;
        });
      } else {
        log(status);
      }
    });

    // 监听录音音量
    final amplitudesResponseSubscription =
        recorder.responseFromAmplitudeListener((recordResponse) {
      setState(() {
        volume = double.parse(recordResponse.msg!) * 1.1;
        if (overlayEntry != null) {
          overlayEntry!.markNeedsBuild();
        }
      });
    });

    subscriptions = [responseSubscription, amplitudesResponseSubscription];

    isInit = true;
  }

  /// 停止录音
  void _stop() {
    setState(() {
      isRecording = false;
    });
    recorder.stopRecord();
    setState(() {
      soundTipsText = LocaleKeys.chatBarSoundCancel.tr;
    });
  }

  /// 回调发送录音
  _sendSound({
    required String path,
    required int duration,
  }) {
    if (duration > 0) {
      if (!isCancelSend) {
        if (widget.onSoundSend != null) {
          widget.onSoundSend!(path, duration);
        }
        widget.onDownBottom();
      } else {
        isCancelSend = false;
      }
    } else {
      Loading.toast(LocaleKeys.chatBarSoundTooShort.tr);
    }
  }

  /// 组件释放
  @override
  dispose() {
    for (var subscription in subscriptions) {
      subscription.cancel();
    }
    super.dispose();
  }

  //////////////////////////////////////////////////////////////
  /// UI 事件

  /// 事件 点击触发授权初始
  Future<void> onTapDown(detail) async {
    if (!isInit) {
      var microphone = await Privilege.microphone();
      if (!microphone.result) {
        await ActionDialog.normal(
          context: context,
          content: Text(microphone.message),
          confirm: const Text('Setting'),
          cancel: const Text('Not allowed'),
          onConfirm: () => Privilege.openSettings(),
        );
        return;
      }
      _initRecordSound();
    }
  }

  /// 事件 长按开始
  void onLongPressStart(_) {
    if (isInit) {
      setState(() {
        soundTipsText = LocaleKeys.chatBarSoundCancel.tr;
      });
      startTime = DateTime.now();
      recorder.startRecord();
      _buildOverLayView(context);
    }
  }

  /// 事件 上划取消
  void onLongPressUpdate(e) {
    double height = MediaQuery.of(context).size.height * 0.5 - 240;
    double dy = e.localPosition.dy;
    String tapReleaseCancelTip = LocaleKeys.chatBarSoundTapReleaseCancel.tr;

    if (dy.abs() > height) {
      if (mounted && soundTipsText != tapReleaseCancelTip) {
        setState(() {
          soundTipsText = tapReleaseCancelTip;
        });
      }
    } else {
      if (mounted && soundTipsText == tapReleaseCancelTip) {
        setState(() {
          soundTipsText = LocaleKeys.chatBarSoundCancel.tr;
        });
      }
    }
  }

  /// 事件 结束录音
  onLongPressEnd(e) {
    double dy = e.localPosition.dy;
    // 此高度为 160为录音取消组件距离顶部的预留距离
    double height = MediaQuery.of(context).size.height * 0.5 - 240;
    if (dy.abs() > height) {
      isCancelSend = true;
    } else {
      isCancelSend = false;
    }
    if (overlayEntry != null) {
      overlayEntry!.remove();
      overlayEntry = null;
    }
    // 如果持续时间太短，则没有从 FlutterPluginRecord 收到 onStop。
    if (DateTime.now().difference(startTime).inSeconds < 1) {
      isCancelSend = true;
      Loading.toast(LocaleKeys.chatBarSoundTooShort.tr);
    }
    _stop();
  }

  /// 事件 取消录音
  void onLonePressCancel() {
    if (isRecording) {
      isCancelSend = true;
      if (overlayEntry != null) {
        overlayEntry!.remove();
        overlayEntry = null;
      }
      _stop();
    }
  }

  //////////////////////////////////////////////////////////////
  /// 视图

  // 浮动层
  void _buildOverLayView(BuildContext context) {
    if (overlayEntry == null) {
      overlayEntry = OverlayEntry(builder: (content) {
        return Positioned(
          top: 0,
          left: 0,
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          child: Material(
            color: Colors.transparent,
            type: MaterialType.canvas,
            child: Center(
              child: Opacity(
                opacity: 0.8,
                child: Container(
                  width: 160,
                  height: 160,
                  decoration: const BoxDecoration(
                    color: Color(0xff77797A),
                    borderRadius: BorderRadius.all(Radius.circular(20.0)),
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      const SizedBox(
                        height: 20,
                      ),
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.end,
                        mainAxisSize: MainAxisSize.min,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Container(
                            margin: const EdgeInsets.only(top: 10),
                            child: Image.asset(
                              "images/microphone.png",
                              width: 50,
                              height: 60,
                              package: 'flutter_plugin_record_plus',
                            ),
                          ),
                          ClipRect(
                            clipBehavior: Clip.hardEdge,
                            child: Align(
                              heightFactor: max(min(volume, 1), 0.1),
                              alignment: Alignment.bottomCenter,
                              child: SizedBox(
                                width: 50,
                                height: 60,
                                child: Image.asset(
                                  "images/voice_volume_total.png",
                                  width: 50,
                                  height: 60,
                                  package: 'flutter_plugin_record_plus',
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(
                        height: 20,
                      ),
                      Text(
                        soundTipsText,
                        style: const TextStyle(
                          fontStyle: FontStyle.normal,
                          color: Colors.white,
                          fontSize: 14,
                        ),
                      )
                    ],
                  ),
                ),
              ),
            ),
          ),
        );
      });
      Overlay.of(context).insert(overlayEntry!);
    }
  }

  // 主视图
  Widget _buildView() {
    return GestureDetector(
      // 事件
      onTapDown: onTapDown,
      onLongPressStart: onLongPressStart,
      onLongPressMoveUpdate: onLongPressUpdate,
      onLongPressEnd: onLongPressEnd,
      onLongPressCancel: onLonePressCancel,

      // 组件
      child: TextWidget.body1(isRecording
              ? LocaleKeys.chatBarSoundRelease.tr
              : LocaleKeys.chatBarSoundTap.tr)
          .center()
          .decorated(
            borderRadius: BorderRadius.circular(5),
            border: Border.all(color: AppColors.secondary),
            color: AppColors.onPrimary,
          )
          .height(38),
    );
  }

  @override
  Widget build(BuildContext context) {
    return _buildView();
  }
}
